window.addEventListener("DOMContentLoaded", () => {
	let hasBoundKeydown = false;
	const observer = new MutationObserver((mutations) => {
		const inputBox = document.querySelector('[contenteditable="true"]');

		if (inputBox && !hasBoundKeydown) {
			hasBoundKeydown = true;
			// 绑定键盘事件监听AA
			inputHandle(inputBox);
			observer.disconnect(); // 停止检测
		}
	});
	observer.observe(document.body, { childList: true, subtree: true });
});

function inputHandle(inputBox) {
	inputBox.addEventListener(
		"keydown",
		(e) => {
			if (e.key === "Enter" && !e.shiftKey) {
				e.stopImmediatePropagation();
				e.preventDefault();
				const originalMessage = inputBox.textContent.trim();
				let translatedMessage = originalMessage;
				if (/[一-龥]/.test(originalMessage)) {
					translatedMessage = "Hello, this is the translated text.";
				}

				const bilingualMessage = `${originalMessage}\n${translatedMessage}`;

				const dataTransfer = new DataTransfer();
				dataTransfer.setData("text/plain", bilingualMessage);
				inputBox.dispatchEvent(
					new ClipboardEvent("paste", {
						clipboardData: dataTransfer,
						bubbles: true,
					}),
				);

				// 需要根据实际情况获取按钮的结构
				const sendBtn = document.querySelector(
					'[aria-label="Press Enter to send"]',
				);
				if (sendBtn) {
					sendBtn.click();
				}
			}
		},
		true,
	);
}
